<template>
  <Form
    class="xtx-form"
    autocomplete="off"
    :validation-schema="mySchema"
    v-slot="{ errors }"
    ref="target"
  >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
          :class="{ err: errors.account }"
          name="account"
          v-model="form.account"
          class="input"
          type="text"
          placeholder="请输入用户名"
        />
      </div>
      <div class="error" v-show="errors.account">{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          :class="{ err: errors.mobile }"
          name="mobile"
          v-model="form.mobile"
          class="input"
          type="text"
          placeholder="请输入手机号"
        />
      </div>
      <div class="error" v-show="errors.mobile">{{ errors.mobile }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          :class="{ err: errors.code }"
          name="code"
          v-model="form.code"
          class="input"
          type="text"
          placeholder="请输入验证码"
        />
        <span class="code" @click="send">{{
          time === 0 ? "发送验证码" : `${time}秒后发送`
        }}</span>
      </div>
      <div class="error" v-show="errors.code">{{ errors.code }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          :class="{ err: errors.password }"
          name="password"
          v-model="form.password"
          class="input"
          type="password"
          placeholder="请输入密码"
        />
      </div>
      <div class="error" v-show="errors.password">{{ errors.password }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          :class="{ err: errors.rePassword }"
          name="rePassword"
          v-model="form.rePassword"
          class="input"
          type="password"
          placeholder="请确认密码"
        />
      </div>
      <div class="error" v-show="errors.rePassword">{{ errors.rePassword }}</div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { reactive, ref, onUnmounted } from 'vue'
import schema from '@/utils/vee-validate-schema'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { useIntervalFn } from '@vueuse/core'
import Message from '@/components/library/Message'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 表单信息对象
    const form = reactive({
      account: '',
      password: '',
      mobile: '',
      code: '',
      rePassword: ''
    })
    // 校验规则
    const mySchema = reactive({
      account: schema.accountApi,
      password: schema.password,
      mobile: schema.mobile,
      code: schema.code,
      rePassword: schema.rePassword
    })
    // 验证码倒计时
    const time = ref(0)
    const { pause, resume } = useIntervalFn(
      () => {
        time.value--
        if (time.value <= 0) {
          pause()
        }
      },
      1000,
      false
    )
    onUnmounted(() => {
      pause()
    })
    // 发送验证码
    const target = ref(null)
    const send = async () => {
      const valid = mySchema.mobile(form.mobile)
      if (valid === true) {
        try {
          if (time.value === 0) {
            await userQQPatchCode(form.mobile)
            Message({ type: 'success', text: '发送成功' })
            time.value = 60
            resume()
          }
        } catch (e) {
          Message({ type: 'error', text: e.response.data.message })
        }
      } else {
        // 失败，使用vee的错误函数显示错误信息 setFieldError(字段,错误信息)
        target.value.setFieldError('mobile', valid)
      }
    }
    // 立即提交
    const router = useRouter()
    const store = useStore()
    const submit = async () => {
      const valid = await target.value.validate()
      if (valid) {
        try {
          const data = await userQQPatchLogin({ unionId: props.unionId, ...form })
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', {
            id,
            avatar,
            nickname,
            account,
            mobile,
            token
          })
          store.dispatch('cart/mergeCart').then(() => {
            Message({ type: 'success', text: '完善信息成功' })
            router.push(store.state.user.redirectUrl)
          })
        } catch (err) {
          Message({ type: 'error', text: '绑定失败' })
        }
      }
    }
    return { form, mySchema, send, submit, time, target }
  }
}
</script>

<style scoped lang="less">
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
